package com.cehome.cloudbox.flowalbe;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.cehome.cloudbox.constans.ExtensionTaskProperties;
import com.cehome.cloudbox.constans.MsgConstants;
import com.cehome.cloudbox.enums.ProcCommentTypeEnum;
import com.cehome.cloudbox.exception.BizException;
import com.cehome.cloudbox.service.IProcCommonService;
import org.flowable.bpmn.model.ExtensionElement;
import org.flowable.bpmn.model.FlowElement;
import org.flowable.common.engine.impl.identity.Authentication;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class BusinessUtil {

    @Autowired
    RuntimeService runtimeService;

    @Autowired
    FlowableTaskService flowableTaskService;

    @Autowired
    BpmnModelUtil bpmnModelUtil;


    @Resource
    private IProcCommonService iProcCommonService;

    //流程定义key
    public void startProcess(String processInstanceId){
        //发起流程
        Map<String,Object> variables=new HashMap<String,Object>();
        //发起者身份id，这里需要替换成业务中需要，参数value不能替换
        //variables.put(ExtensionTaskProperties.FLOWABLE_ASSIGNEE,"1");
        variables.put("zhihui","5,6,7");
        List<String> list= new ArrayList<>();
        list.add("1");
        list.add("2");
        list.add("3");
        variables.put("huiqian",list);
        //设置startUserId
        String startUserId = "1";
        Authentication.setAuthenticatedUserId(startUserId);
        //获取下一任务节点信息
        ProcessInstance processInstance = runtimeService.startProcessInstanceById(processInstanceId,variables);
        try {
           String xml= bpmnModelUtil.getDeploymentModelImageByModelId(processInstance.getDeploymentId());
           System.out.println(xml);
        }catch (Exception e) {

        }
//        System.out.println(processInstance.getId());
//        //获取下一任务节点信息
//        Task task =flowableTaskService.getTaskByProcessInstanceId(processInstanceId);
//        //获取流程节点数据
//        FlowElement flowElement = flowableTaskService.getNodeByTask(task,"now");
//        //获取自定义的参数信息
//        Map<String, List<ExtensionElement>> extensionElements = flowElement.getExtensionElements();
//        //获取下节点的自定义参数设置
//        FlowableReturnModel flowableReturnModel = getModel(flowElement.getId(),extensionElements);
//        return flowableReturnModel;
    }


    //用户的流程待办
    public List<Object> getInstanceTo(String userId){
        //自己判断，所有数据的时候不用筛选userId
        String sql = "SELECT\n" +
                "            a.PROC_INST_ID_ processInstanceId,\n" +
                "            c.NAME_ name,\n" +
                "            c.ID_ versionName,\n" +
                "            IFNULL(b.START_USER_ID_,'') startUserId,\n" +
                "            b.START_TIME_ startTime,\n" +
                "            c.VERSION_ version,\n" +
                "            a.NAME_ currentNode,\n" +
                "            IFNULL(a.ASSIGNEE_,'') assignee,\n" +
                "            b.SUSPENSION_STATE_ status,\n" +
                "            d.TEXT_ title\n" +
                "        FROM\n" +
                "            ACT_RU_TASK a\n" +
                "        LEFT JOIN ACT_RU_EXECUTION b ON a.PROC_INST_ID_ = b.ID_\n" +
                "        LEFT JOIN ACT_RE_PROCDEF c ON a.PROC_DEF_ID_ = c.ID_\n" +
                "        LEFT JOIN ACT_HI_VARINST d ON a.PROC_INST_ID_ = d.PROC_INST_ID_ and b.START_USER_ID_=#{userId}";
        return null;
    }

    public boolean validateProcessIsStop(String processinstId){
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processinstId).active().singleResult();
        if(processInstance==null){
            return  true;
        }
        return false;
    }

    //所有待办列表中返回了流程id，根据流程id获取当前指定人的审批任务信息
    public Task getTask(String processInstanceId,String userId){
        if(true==validateProcessIsStop(processInstanceId)){
            throw new BizException("未流程已结束");
        }
        List<Task> taskListByProcessInstanceId = flowableTaskService .getTaskListByProcessInstanceId(processInstanceId);
        for(Task task : taskListByProcessInstanceId){
            if(userId.equals(task.getAssignee())){
                return task;
            }
        }
        throw new BizException("未找到流程任务");
    }

    //审批通过，不通过有撤回按钮，通用用户发起流程没有选择审批人
    public void approveAgree(ApproveModel approveModel){
        if(true==validateProcessIsStop(approveModel.getProcessInstanceId())){
            throw new BizException("流程已结束");
        }
        String userId = "11111";
        Task task = flowableTaskService.getTaskByTaskId(approveModel.getTaskId());
        //获取流程节点数据
        FlowElement flowElement = flowableTaskService.getNodeByTask(task,"now");
        //获取自定义的参数信息
        Map<String, List<ExtensionElement>> extensionElements = flowElement.getExtensionElements();
        //获取下节点的自定义参数设置
        FlowableReturnModel flowableReturnModel = getModel(flowElement.getId(),extensionElements);
        //补充下节点参数信息
        Map<String,Object> map = new HashMap<>();
        Map<String,Object> mapInistanceParam = approveModel.getMapInistanceParam();
        //判断是单签还是会签
        if(ObjectUtils.isNotEmpty(flowableReturnModel.getAssignListName())){
            if(flowableReturnModel.getIsHuiqian()){
                //下级节点的审批入参会签
                map.put(flowableReturnModel.getAssignListName(),mapInistanceParam.get(flowableReturnModel.getAssignListName()));
            }else{
                //下级节点的审批入参单签
                map.put(flowableReturnModel.getAssignListName(),mapInistanceParam.get(flowableReturnModel.getAssignListName()));
            }
        }
        // 添加意见
        iProcCommonService.addTaskHandleComment(task.getId(), task.getProcessInstanceId(),task.getName(), "", userId);
        //完成当前节点审批，map入参可以自定义增加
        flowableTaskService.finishCurrentTaskByTaskId(task,map);

       /* //获取下一节点参数信息，返回给前端
        FlowElement flowElementNext = flowableTaskService.getNodeByTask(task,"next");
        //获取自定义的参数信息
        Map<String, List<ExtensionElement>> extensionElementsNext = flowElement.getExtensionElements();
        //获取下节点的自定义参数设置
        FlowableReturnModel flowableReturnModelNext = getModel(flowElementNext.getId(),extensionElementsNext);
        return flowableReturnModelNext;*/
    }

    //根据流程获取流程中的变量
    public Map<String,Object> getParamsByInstanceId(String processinstId){
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processinstId).active().singleResult();
        return processInstance.getProcessVariables();
    }

    public FlowableReturnModel getModel(String id,Map<String, List<ExtensionElement>> map){
        if(null == map || map.size()<=0){
            throw new BizException(MsgConstants.ERR_E099);
        }
        FlowableReturnModel flowableReturnModel = new FlowableReturnModel();
        ExtensionElement extensionElement = null;
        //获取下一参数节点的参数名称
        List<ExtensionElement> assignListNames = map.get(id+"nextParamName");
        if(null!=assignListNames && assignListNames.size()>0){
            extensionElement = assignListNames.get(0);
            flowableReturnModel.setAssignListName(extensionElement.getElementText());
        }

        //判断下一节点的审批形式是串签还是会签，
        List<ExtensionElement> huiqs = map.get(id+"isHuiqian");
        if(null!=huiqs && huiqs.size()>0){
            extensionElement = huiqs.get(0);
            flowableReturnModel.setIsHuiqian(Boolean.valueOf(extensionElement.getElementText()));
        }
        return flowableReturnModel;
    }

}
